﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Hxsoft.AppV1.Module;

namespace Hxsoft.AppV1.Admin.LinkManage
{
	public partial class Default : BasePage
    {
        #region LinkClass
        private int _classID;
		private bool _isLoadClassID = false;
		/// <summary>
		/// 当前的站点标识。
		/// </summary>
		protected int ClassID
		{
			get
			{
				if (!_isLoadClassID)
				{
					if (!String.IsNullOrEmpty(Request.QueryString["ClassID"]))
						_classID = Convert.ToInt32(Request.QueryString["ClassID"]);
					_isLoadClassID = true;
				}
				return _classID;
			}
		}

		protected string ClassName
		{
			get {
				return LinkClasses.GetItem(ClassID).ClassName;
			}
		}


		protected void Page_Load(object sender, EventArgs e)
		{
			if (Links.GetManageListRight(ClassID,SiteId))
			{
				if (!IsPostBack)
				{
					LoadList();
					Page.DataBind();
                    BindSiteData();
                    InitSelectedClass();

				}
			}
			else
			{
				Messages.Add(new PageMessage(false, null, PageMessageType.Error, Res.PermissionExceptionMessageTitle, Res.PermissionExceptionMessage));
			}
		}

		protected void pager_PageChanging(object src, Wuqi.Webdiyer.PageChangingEventArgs e)
		{
			pager.CurrentPageIndex = e.NewPageIndex;
			LoadList();
		}

		protected void BtSearch_Click(object sender, EventArgs e)
		{
			pager.CurrentPageIndex = 1;
			LoadList();
		}

		protected void BtReload_Click(object sender, EventArgs e)
		{
			LoadList();
		}

		protected void List_ItemCommand(object source, RepeaterCommandEventArgs e)
		{
			int identifier = GetListItemIdentifier(e.Item);
			string messages = "";

			switch (e.CommandName)
			{
				case "Delete":
					messages = Delete(identifier);
					break;
				case "SetEffective":
					messages = SetEffectiveState(identifier);
					break;
			}

			if (!String.IsNullOrEmpty(messages))
			{
				Messages.Add(new PageMessage(true, null, PageMessageType.Error, Res.OperationErrorTitle, messages));
			}

			LoadList();
		}

		protected void BtDelete_ServerClick(object sender, EventArgs e)
		{
			int identifier;
			string messages = "";

			foreach (RepeaterItem item in List.Items)
			{
				if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
				{
					CheckBox cbSelect = (CheckBox)item.FindControl("CbSelect");
					if (!cbSelect.Checked)
						continue;

					identifier = GetListItemIdentifier(item);
					string message = Delete(identifier);

					if (!String.IsNullOrEmpty(message))
						messages += "<li>[" + identifier.ToString() + "]" + message + "</li>";
				}
			}

			if (!String.IsNullOrEmpty(messages))
			{
				Messages.Add(new PageMessage(true, null, PageMessageType.Error, Res.OperationErrorTitle, messages));
			}

			LoadList();
		}

		protected void BtSeffiective_ServerClick(object sender, EventArgs e)
		{
			int identifier;
			string messages = "";

			foreach (RepeaterItem item in List.Items)
			{
				if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
				{
					CheckBox cbSelect = (CheckBox)item.FindControl("CbSelect");
					if (!cbSelect.Checked)
						continue;
					identifier = GetListItemIdentifier(item);
					string message = SetEffectiveState(identifier);

					if (!String.IsNullOrEmpty(message))
						messages += "<li>[" + identifier.ToString() + "]" + message + "</li>";
				}
			}
			if (!String.IsNullOrEmpty(messages))
			{
				Messages.Add(new PageMessage(true, null, PageMessageType.Error, Res.OperationErrorTitle, messages));
			}

			LoadList();
		}

		/// <summary>
		/// 加载列表。
		/// </summary>
		protected void LoadList()
		{
			PaginationInfo<List<Links.LinkForManageList>> pageInfo =
				Links.GetPaginationManageList(ClassID, IntExtensions.ParseOrNull(CtrChannelIds.SelectedValue), TbKeyword.Text, pager.PageSize, pager.CurrentPageIndex);

			pager.RecordCount = pageInfo.RecordCount;

			List.DataSource = pageInfo.Records;
			List.DataBind();

			pager.CustomInfoHTML = Helper.GetPagerCustomInfoHtml<List<Links.LinkForManageList>>(pageInfo);
		}

		protected string ItemChannels
		{
			get
			{
				var ids = Eval("ChannelIds", "").Trim();
				if (string.IsNullOrEmpty(ids)) return "";
				
				var channelIds = StringExtensions.CasingDecompound<string>(ids, Companies.OperationTypeSeparator);
				var channel = "";
				foreach (var id in channelIds)
				{
					if (string.IsNullOrEmpty(id)) continue;
					channel += (string.IsNullOrEmpty(channel) ? "" : ",") + Dictionaries.GetNameById(SiteId, Common.DicClassName_ChannelCategory, int.Parse(id));
				}
				return channel;
			}
		}

		/// <summary>
		/// 取得 ListItem 的标识符。
		/// </summary>
		/// <param name="item">列表的 ListItem。</param>
		/// <returns>ListItem 的标识符。</returns>
		protected int GetListItemIdentifier(RepeaterItem item)
		{
			int identifier;
			HiddenField control;

			control = (HiddenField)item.FindControl("Identifier_LinkID");
			identifier = Convert.ToInt32(control.Value);

			return identifier;
		}

		/// <summary>
		/// 删除指定的信息
		/// </summary>
		/// <param name="identifier">要删除信息的标识符。</param>
		/// <returns>如果删除发生错误则返回错误消息。</returns>
		protected string Delete(int identifier)
		{
			if (Links.GetDeleteRight(Links.GetItem(identifier)))
			{
				Links.Delete(identifier);
				return null;
			}
			else
				return string.Format(Res.PermissionException_DeleteAppointedObject, identifier);
		}

		/// <summary>
		/// 修改有效状态
		/// </summary>
		/// <param name="identifier"></param>
		/// <returns>如果发生错误则返回错误消息。</returns>
		public string SetEffectiveState(int identifier)
		{
			if (Links.GetSetEffectiveStateRight(Links.GetItem(identifier)))
			{
				Links.SetEffectiveState(identifier);
				return null;
			}
			else
				return string.Format(Res.PermissionException_SettingAppointedObject, identifier);
		}
		
		/// <summary>
		/// 移动链接
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		protected void BtMove_Click(object sender, EventArgs e)
		{
            CopyAndMove(false);
		}

        protected void BtCopyAndMove_Click(object sender, EventArgs e)
        {
            CopyAndMove(true);
        }

        protected void CopyAndMove(bool isMove)
        {
            if (String.IsNullOrEmpty(SelectLinkClassIds))
            {
                LinkClassView.DataBind();
                Messages.Add(new PageMessage(true, null, PageMessageType.Prompt, "", "请选择目标链接类!"));
                return;
            }
            
            int identifier;
            string messages = "";
            string messagesErr = "";
            string[] ids = SelectLinkClassIds.Split(",");
            Link link = null;
            string message = "";

            var linkId = IntExtensions.ParseOrNull(HddLinkId.Value);
            if (linkId.HasValue)
            {
                link = Links.GetItem(linkId.Value);
                if (isMove)
                    message = Delete(linkId.Value); //删除当前

                if (!String.IsNullOrEmpty(message))
                    messagesErr += "<li>[" + linkId.Value.ToString() + "]" + message + "</li>";
                else
                {
                    for (int i = 0; i < ids.Length - 1; i++)
                    {
                        if (string.IsNullOrEmpty(ids[i])) continue;

                        var linkclassId=IntExtensions.ParseOrNull(ids[i]);
                        if(!linkclassId.HasValue) continue;

                        var linkclassName = LinkClasses.GetNameById(linkclassId.Value);

                        if (RightValidate(linkclassId.Value) && IsValid)
                        {
                            try
                            {
                                link.ClassId = linkclassId.Value;
                                link = Links.Insert(link);
                                messages += "<li>向[" + linkclassName + "]添加[" + link.Title + "]成功!</li>";
                            } catch
                            {
                                messages += "<li>向[" + linkclassName + "]添加[" + link.Title + "]失败!</li>";
                            }
                        }
                    }
                }
            }
            else
            {
                foreach (RepeaterItem item in List.Items)
                {
                    if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
                    {
                        CheckBox cbSelect = (CheckBox)item.FindControl("CbSelect");
                        if (!cbSelect.Checked)
                            continue;

                        identifier = GetListItemIdentifier(item);
                        link = (Link)Links.GetItem(identifier);
                       
                        if (isMove)
                            message = Delete(identifier); //删除

                        if (!String.IsNullOrEmpty(message))
                            messagesErr += "<li>" + message + "</li>";
                        else
                        {
                            for (int i = 0; i < ids.Length - 1; i++)
                            {

                                if (string.IsNullOrEmpty(ids[i])) continue;

                                var linkclassId = IntExtensions.ParseOrNull(ids[i]);
                                if (!linkclassId.HasValue) continue;

                                var linkclassName = LinkClasses.GetNameById(linkclassId.Value);

                                if (RightValidate(linkclassId.Value) && IsValid)
                                {
                                    try
                                    {
                                        link.ClassId = linkclassId.Value;
                                        link = Links.Insert(link);
                                        messages += "<li>向[" + linkclassName + "]添加[" + link.Title + "]成功!</li>";
                                    }
                                    catch
                                    {
                                        messages += "<li>向[" + linkclassName + "]添加[" + link.Title + "]失败!</li>";
                                    }
                                }
                            }
                        }
                    }
                }
            }

            //显示错误信息
            if (!String.IsNullOrEmpty(messagesErr))
            {
                Messages.Add(new PageMessage(true, null, PageMessageType.Error, Res.OperationErrorTitle, messagesErr));
            }
            if (!String.IsNullOrEmpty(messages))
            {
                Messages.Add(new PageMessage(true, null, PageMessageType.Prompt, Res.OperationCompleteTitle, messages));
            }

            LoadList();

            ScriptManager.RegisterStartupScript(this, this.GetType(), "Init_CloseDiv", "CloseDiv();", true);
           
        }


		/// <summary>
		/// 返回权限验证结果，如果验证失败则显示消息提示。
		/// </summary>
		/// <returns>布尔值代表权限验证是否通过。</returns>
		private bool RightValidate(int classID)
		{
			bool right = Links.GetInsertRight(new Link { ClassId = classID });
			if (!right)
			{
				Messages.Add(new PageMessage(false, null, PageMessageType.Error, Res.PermissionExceptionMessageTitle, Res.PermissionExceptionMessage));
			}
			return right;
        }

        #endregion

        #region


        protected string SelectLinkClassIds
        {
            get {
                TreeView tree = (TreeView)this.LinkClassView;
                TreeNodeCollection col = tree.CheckedNodes;
                TreeNode node = null;
                string classIds = "";
                for (int i = 0; i < col.Count; i++)
                {
                    node = (TreeNode)col[i];
                    classIds += node.Value + ",";
                }
                return classIds;
            }
        }




        /// <summary>
		/// 链接的地址。
		/// </summary>
		protected string LinkUrl
		{
			get
			{
				return Request["LinkUrl"];
			}
		}

		/// <summary>
		/// 站点标识的字段。
		/// </summary>
		protected string ClassIDQueryStringField
		{
			get
			{
				return Request["ClassIDQueryStringField"];
			}
		}

		/// <summary>
		/// 链接的目标。
		/// </summary>
		protected string LinkTarget
		{
			get
			{
				string linkTarget = Request["LinkTarget"];
				return string.IsNullOrEmpty(linkTarget) ? "ContentFrame" : linkTarget;
			}
		}

		/// <summary>
		/// 选中的节点。
		/// </summary>
		protected int? SelectedClassID
		{
			get
			{
				string selectedClassID = Request["SelectedClassID"];
				if (string.IsNullOrEmpty(selectedClassID))
					return null;
				else
					return Convert.ToInt32(selectedClassID);
			}
		}	

        /// <summary>
		/// 初始化选择类别。
		/// </summary>
		protected void InitSelectedClass()
		{
			LinkClass pathNode = null;
			if (SelectedClassID.HasValue)
				pathNode = LinkClasses.GetItem(SelectedClassID.Value, true);

			if (pathNode != null)
			{
				TreeNode node = ExpandNode(pathNode);
				if (node != null) node.Selected = true;
			}
		}

		protected TreeNode ExpandNode(LinkClass pathNode)
		{
			TreeNode node;
			if (pathNode.Parent == null)
			{
				node = FindNode(LinkClassView.Nodes, pathNode.SiteId.ToString());
				if (node != null)
					node.Expand();

				node = FindNode(node.ChildNodes, pathNode.ClassId.ToString());
				return node;
			}

			node = ExpandNode(pathNode.Parent);
			if (node == null) return null;
			node.Expand();

			node = FindNode(node.ChildNodes, pathNode.ClassId.ToString());
			return node;
		}

		/// <summary>
		/// 查找具有指定值的节点。
		/// </summary>
		/// <param name="nodes">节点集合。</param>
		/// <param name="value">查找的节点值。</param>
		/// <returns>找到的节点。</returns>
		protected TreeNode FindNode(TreeNodeCollection nodes, string value)
		{
			foreach (TreeNode node in nodes)
			{
				if (node.Value == value)
					return node;
			}
			return null;
		}

		/// <summary>
		/// 绑定站点数据。
		/// </summary>
		protected void BindSiteData()
		{
			List<Site> sites = Sites.GetItems();

			foreach (Module.Site site in sites)
			{
                if (site.SiteId != SiteId.Value) continue;
				// 权限验证
				if (!Links.GetRootManageListRight(site.SiteId))
					continue;

				TreeNode node = new TreeNode();
				node.Text = site.SiteName;
				node.Value = site.SiteId.ToString();
				node.SelectAction = TreeNodeSelectAction.None;
				node.PopulateOnDemand = true;

				LinkClassView.Nodes.Add(node);
			}
		}
        protected void LinkClassView_TreeNodePopulate(object sender, TreeNodeEventArgs e)
		{
			BindLinkClassData(e.Node);
		}
        /// <summary>
		/// 绑定链接类别数据。
		/// </summary>
		/// <param name="parentNode">父级节点。</param>
		protected  void BindLinkClassData(TreeNode parentNode)
		{
            parentNode.ChildNodes.Clear();
			List<LinkClass> childClasses;

			if (parentNode.Depth == 0)
				childClasses = LinkClasses.GetRoots(int.Parse(parentNode.Value));
			else
				childClasses = LinkClasses.GetChildren(int.Parse(parentNode.Value));

			foreach (LinkClass childClass in childClasses)
			{
				if (!Links.GetManageListRight(childClass.ClassId,childClass.SiteId))
					continue;

				if (childClass.ClassId == ClassID)
					continue;

				TreeNode node = new TreeNode();
				node.Text = childClass.ClassName;
				node.Value = childClass.ClassId.ToString();



				if (childClass.ChildCount > 0)
				{
					node.SelectAction = TreeNodeSelectAction.None;
					node.PopulateOnDemand = true;
				}
				else
				{									
					node.PopulateOnDemand = false;
					node.ToolTip = childClass.Memo;
					node.SelectAction = TreeNodeSelectAction.None;
				}

				parentNode.ChildNodes.Add(node);
			}
		}
        #endregion              
    }
}
